package thread;

import java.util.IdentityHashMap;

/**
 * @author: 成金乘
 * @date: 2022/12/30 14:12
 * @description:
 */
//提供：可以通过 synchronized 或者 Lock 来实现一个死锁代码。
//所谓的死锁就是线程一拥有锁1，线程二拥有锁2，双方在拥有自身锁的同时尝试获取对方的锁，最终两个线程就会进入无线等待的状态，这就是死锁。
public class ThreadDemo10 {
    public static void main(String[] args) {
        Object lock1 = new Object();
        Object lock2 = new Object();

        Thread t1 = new Thread(()->{
            synchronized (lock1){
                System.out.println(Thread.currentThread().getName() + ":已经获取到lock1");
                try {
                    Thread.sleep(100);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                synchronized (lock2){
                    System.out.println(Thread.currentThread().getName() + ":已经获取到lock2");
                }
            }
        },"t1");
        Thread t2 = new Thread(()->{
            synchronized (lock2){
                System.out.println(Thread.currentThread().getName() + ":已经获取到lock2");
                try {
                    Thread.sleep(100);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                synchronized (lock1){
                    System.out.println(Thread.currentThread().getName() + ":已经获取到lock1");
                }
            }
        },"t2");
        t1.start();
        t2.start();
    }

}
